package com.sgq.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sgq.config.redis.RedisService;
import com.sgq.entity.User;
import com.sgq.utils.JwtUtils;
import com.sgq.utils.LoginResult;
import com.sgq.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: 83778
 * @date: 2024-09-18 9:38
 * @desc: 登录成功后做什么操作
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        //设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        //获取当登录用户信息
        User user = (User) authentication.getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(user);
        //创造一个LoginResult对象
        LoginResult loginResult = new LoginResult();
        loginResult.setId(user.getId());
        loginResult.setToken(token);
        loginResult.setExpireTime(jwtUtils.getExpTimeMillis());
        loginResult.setCode(ResultCode.SUCCESS);
        //消除循环引用
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        //设置了一个token-
        redisService.set(redisService.getPrefix()+token,token,jwtUtils.getExpiration() * 60 );
    }
}
